package com.atguigu.controller;


import com.atguigu.entity.CartInfo;
import com.atguigu.result.RetVal;
import com.atguigu.service.CartInfoService;
import com.atguigu.util.AuthContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 购物车表 用户登录系统时更新冗余 前端控制器
 * </p>
 *
 * @author hachimen
 * @since 2021-09-04
 */
@RestController
@RequestMapping("/cart/")
public class CartInfoController {

    @Autowired
    private CartInfoService cartInfoService;
    //添加购物车
    @PostMapping("addToCart/{skuId}/{skuNum}")
    public RetVal addToCart(@PathVariable Long skuId, @PathVariable Integer skuNum, HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        if(StringUtils.isEmpty(userId)){
            userId = AuthContextHolder.getUserTempId(request);
        }
        cartInfoService.addToCart(skuId,skuNum,userId);
        return RetVal.ok();
    }
    //购物车列表展示
    @GetMapping("getCartList")
    public RetVal cartList(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        String userTempId = AuthContextHolder.getUserTempId(request);
        List<CartInfo> list = cartInfoService.cartList(userId,userTempId);
        return RetVal.ok(list);
    }

    // 删除购物车
    @DeleteMapping("deleteCart/{skuId}")
    public RetVal deleteCartInfo(@PathVariable Long skuId,
                                 HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        if(StringUtils.isEmpty(userId)){
            userId = AuthContextHolder.getUserTempId(request);
        }
        cartInfoService.deleteCartInfo(userId,skuId);
        return RetVal.ok();
    }

    //商品的选中
    @GetMapping("checkCart/{skuId}/{isChecked}")
    public RetVal checkCart(@PathVariable Long skuId,@PathVariable Integer isChecked,HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        if(StringUtils.isEmpty(userId)){
            userId = AuthContextHolder.getUserTempId(request);
        }
        cartInfoService.checkCart(userId,skuId,isChecked);
        return RetVal.ok();
    }
    //查询选中的商品信息
    @GetMapping("getSelectedProduct/{userId}")
    public List<CartInfo> getSelectedProduct(@PathVariable String userId){
        return cartInfoService.getSelectedProduct(userId);
    }
    //从数据库中查询购物车缓存信息
    @GetMapping("queryFromDbToRedis/{userId}")
    public List<CartInfo> queryFromDbToRedis(@PathVariable String userId){
        return cartInfoService.queryDBCartListToRedis(userId);
    }
}

